<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
  import { echarts, ECOption, graphicColors, colors } from '@/hooks/core/useECharts';
  import { IDataShow } from '@/api/types';
  import { useAppSettingStore } from '@/store/module/useAppSettingStore';
  import { isDark } from '@/hooks/core/useToggleDark';
  import { useMobile } from '@/hooks/core/useMobile';
  import { useFullscreen } from "@vueuse/core";

  const ranInt = Math.floor(Math.random() * graphicColors.length) as unknown as number;

  const props = withDefaults(defineProps<{ showData: IDataShow }>(), {
    //@ts-ignore
    showData: {} as IDataShow,
  });
  let chartInstance: Recordable;
  const currentPage = ref(1); // 当前显示的页数
  let pageSize = ref(5);
  const totalPage = computed(() => {
    return props.showData.disData.length % pageSize.value === 0
      ? props.showData.disData.length / pageSize.value
      : props.showData.disData.length / pageSize.value + 1;
  }); // 一共有多少页
  let timerId: NodeJS.Timer; // 定时器的标识
  const displayBar_ref = ref<HTMLElement>(null!);
  const initChart = () => {
    try {
      chartInstance = echarts.init(displayBar_ref.value);
    } catch (e) {}
    // 对图表初始化配置的控制
    const initOption = {
      color: colors,
      title: {
        left: 'center',
        bottom: 10,
        textStyle: {
          color: '#fff',
          textBorderColor: 'black',
          textBorderWidth: 1,
        },
      },
      grid: {
        top: '10%',
        left: '5%',
        right: '6%',
        bottom: '20%',
        containLabel: true, // 距离是包含坐标轴上的文字
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          color: '#fff',
        },
        axisLine: {
          lineStyle: {
            color: '#fff',
          },
        },
      },
      yAxis: {
        type: 'value',
        name: '单位（人次）',
        nameLocation: 'start',
        nameTextStyle: {
          color: '#fff',
          fontStyle: 'oblique',
          align: 'center',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#fff',
          },
          symbol: ['none', 'arrow'],
        },
        axisLabel: {
          color: '#fff',
          margin: 12,
        },
        splitLine: {
          show: false,
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          z: 0,
        },
      },
      series: [
        {
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            color: '#fff',
          },
          itemStyle: {
            // 指明颜色渐变的方向
            // 指明不同百分比之下颜色的值
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              // 百分之0状态之下的颜色值
              {
                offset: 0,
                color: graphicColors[ranInt][0],
              },
              // 百分之100状态之下的颜色值
              {
                offset: 1,
                color: graphicColors[ranInt][1],
              },
            ]),
          },
        },
      ],
    };
    chartInstance.setOption(initOption);
    // 对图表对象进行鼠标事件的监听
    chartInstance.on('mouseover', () => {
      clearInterval(timerId);
    });
    chartInstance.on('mouseout', () => {
      startInterval();
    });
  };
  const screenAdapter = () => {
    const titleFontSize = (displayBar_ref.value.offsetWidth / 100) * 3;
    // 和分辨率大小相关的配置项
    const adapterOption = {
      title: {
        textStyle: {
          fontSize: titleFontSize,
        },
      },
      yAxis: {
        nameTextStyle: {
          fontSize: titleFontSize * 0.7,
        },
      },
      series: [
        {
          barWidth: titleFontSize,
          itemStyle: {
            borderRadius: [
              titleFontSize / 2,
              titleFontSize / 2,
              titleFontSize / 2,
              titleFontSize / 2,
            ],
          },
        },
      ],
    };
    chartInstance.setOption(adapterOption);
    // 手动的调用图表对象的resize 才能产生效果
    chartInstance.resize();
  };
  const destroyed = () => {
    clearInterval(timerId);
    // 在组件销毁的时候, 需要将监听器取消掉
    window.removeEventListener('resize', screenAdapter);
  };
  const updateECharts = (showAll = false) => {
    if (showAll) {
      chartInstance.setOption({
        xAxis: {
          data: props.showData.xAxis,
        },
        series: [
          {
            data: props.showData.disData,
          },
        ],
      });
      return;
    }
    const start = (currentPage.value - 1) * pageSize.value;
    const end = currentPage.value * pageSize.value;
    const showPageData = props.showData.disData.slice(start, end);
    const showPageName = props.showData.xAxis.slice(start, end);
    const dataOption = {
      title: {
        text: '▎' + props.showData.disName,
      },
      xAxis: {
        data: showPageName,
      },
      series: [
        {
          data: showPageData,
        },
      ],
    };
    chartInstance.setOption(dataOption);
  };
  const startInterval = () => {
    if (timerId) {
      clearInterval(timerId);
    }
    timerId = setInterval(() => {
      currentPage.value++;
      if (currentPage.value > totalPage.value) {
        currentPage.value = 1;
        updateECharts(true);
        return;
      }
      updateECharts();
    }, 3000);
  };
  onMounted(() => {
    initChart();
    window.addEventListener('resize', screenAdapter);
    // 在页面加载完成的时候, 主动进行屏幕的适配
    screenAdapter();
    updateECharts();
    startInterval();
  });
  onUnmounted(() => {
    destroyed();
  });
  const isMobile = useMobile();
  watch(isMobile, (value) => {
    chartInstance.setOption({});
  });
  watch(isDark, (value) => {
    chartInstance.setOption({
      tooltip: {
        axisPointer: {
          shadowStyle: {
            color: isDark.value ? '#7e8181' : '#f3f4f6',
          },
        },
      },
    });
  });
</script>

<!-- 商家销量统计的横向柱状图 -->
<template>
  <div class="enter-y" ref="displayBar_ref"></div>
</template>

<style lang="scss"></style>
